﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using seejee_Backendium.Core.Interfaces;
using seejee_Backendium.Core.Models;
using seejee_Backendium.Data.DbContest;
using seejee_Backendium.Data.Services;

namespace seejee_Backendium.WEB.Controllers
{
    [ApiController]
    [Route("api/")]
    [Authorize]
    public class ViewManagementController : ControllerBase
    {
        private readonly IViewManagementService _viewManagementService;
        private readonly ApplicationDbContext _context;
        private readonly IConfiguration _configuration; // 新增字段
        private readonly ILogger<StoreController> _logger;

        public ViewManagementController(IViewManagementService viewManagementService, IConfiguration configuration, ILogger<StoreController> logger, ApplicationDbContext context)
        {
            _viewManagementService = viewManagementService;
            _configuration = configuration;
            _logger = logger; // 
            _context = context; // 注入 ApplicationDbContext
        }
        //获取所有菜单列表
        [HttpGet("bi/menu/list")]
        public IActionResult GetBIMenu([FromQuery] int pageIndex, [FromQuery] int pageSize, [FromQuery] string keyword = "")
        {
            if (pageIndex < 1 || pageSize < 1)
            {
                return BadRequest(new { success = false, message = "参数错误" });
            }
            try
            {
                var menus = _viewManagementService.GetBIMenu(pageIndex, pageSize, keyword);
                return Ok(new { success = true, data = menus });
            }
            catch (Exception ex)
            {
                // 可选：记录日志
                return StatusCode(500, new { success = false, message = ex.Message });
            }

        }
        //获取所有的客户＋id
        [HttpGet("bi/menu/customer")]
        public IActionResult GetBICustomer()
        {
    
            try
            {
                var customers = _viewManagementService.GetBICustomer();
                return Ok(new { success = true, data = customers });
            }
            catch (Exception ex)
            {
                // 可选：记录日志
                return StatusCode(500, new { success = false, message = ex.Message });
            }

        }
        //保存排序
        [HttpPost("menu/save-sort")]
        public async Task<IActionResult> SaveSort([FromBody] BatchSortRequestDTO request)
        {
            try
            {
                // 调用服务层更新排序
                var result = await _viewManagementService.UpdateMenuSort(request.MenuSorts);
                return Ok(new { Success = result, Message = "排序更新成功" });
            }
            catch (Exception ex)
            {
                // 错误处理
                return BadRequest(new { Success = false, Message = ex.Message });
            }
        }
        public class BatchSortRequestDTO
        {
            // 批量排序数据（前端传递的排序数组）
            public List<MenuSortDTO> MenuSorts { get; set; } = new List<MenuSortDTO>();
        }

        //获取所有视图分类名称
        //[HttpGet("view/viewAllName")]
        //public async Task<IActionResult> GetAllViewName()
        //{
        //    try
        //    {
        //        var views = await _viewManagementService.GetAllViewName();
        //        return Ok(new
        //        {
        //            success = true,
        //            data = new
        //            {
        //                code = 200,
        //                items = views,  // 明确使用items字段
        //                total = views.Count()
        //            },
        //            message = "查询成功"
        //        });
        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.LogError(ex, "获取视图名称失败");
        //        return StatusCode(500, new
        //        {
        //            success = false,
        //            message = "获取视图名称失败",
        //            error = ex.Message
        //        });
        //    }
        //}
        //获取所有视图分类名称（支持按客户ID筛选）
        [HttpGet("view/viewAllName")]
        public async Task<IActionResult> GetAllViewName([FromQuery] int? iCusID = null)  // 添加iCusID筛选参数，可空
        {
            try
            {
                // 调用服务层方法时传入筛选条件iCusID
                var views = await _viewManagementService.GetAllViewName(iCusID);
                return Ok(new
                {
                    success = true,
                    data = new
                    {
                        code = 200,
                        items = views,  // 筛选后的视图列表
                        total = views.Count()
                    },
                    message = iCusID.HasValue ? $"查询客户[{iCusID}]关联的视图成功" : "查询全部视图成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取视图名称失败（筛选条件：iCusID={iCusID}）");
                return StatusCode(500, new
                {
                    success = false,
                    message = "获取视图名称失败",
                    error = ex.Message
                });
            }
        }
        // 获取视图分类内容
        [HttpGet("bi/menu/detail/{id}")]
        public async Task<IActionResult> GetView(int id)
        {
            try
            {
                var view = await _viewManagementService.GetView(id);
                return Ok(new
                {
                    success = true,
                    data = new
                    {
                        items = view  // 明确使用items字段

                    },
                    message = "查询成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取存储过程失败");
                return StatusCode(500, new
                {
                    success = false,
                    message = "获取存储过程失败",
                    error = ex.Message
                });
            }
        }
        //添加菜单
        [HttpPost("menu/create")]
        public async Task<IActionResult> InsertMenu([FromBody] MenuInsertDTO menu)
        {
            var menus = new MenuInsertDTO
            {
                cMenuName = menu.cMenuName,
                iCusID = menu.iCusID,
                Perspectives = menu.Perspectives

            };
            var result = _viewManagementService.InsertMenu(menus);
            if (result)
                return Ok(new { Success = true, Message = "菜单添加成功" });
            return StatusCode(500, new { Success = false, Message = "菜单添加失败" });
        }
        //修改视图内容过程
        [HttpPut("/api/menu/update/{id}")]
        public IActionResult UpdateView(int id, [FromBody] MenuInsertDTO menu)
        {
            try
            {
                var result = _viewManagementService.UpdateView(id, menu);
                if (result)
                    return Ok(new { Success = true, Message = "分类更新成功" });
                return StatusCode(500, new { Success = false, Message = "分类更新失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分类更新失败");
                return StatusCode(500, new { Success = false, Message = "服务器错误" });
            }
        }
        // 删除视图分类
        [HttpDelete("menu/delete/{id}")]
        public IActionResult DeleteView(int id)
        {
            try
            {
                var result = _viewManagementService.DeleteView(id);
                if (result)
                    return Ok(new { Success = true, Message = "视图删除成功" });
                return StatusCode(500, new { Success = false, Message = "视图删除失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "视图删除失败");
                return StatusCode(500, new { Success = false, Message = "服务器错误" });
            }
        }
        // 删除视图子类
        [HttpDelete("menu/charts/delete")]
        public IActionResult DeleteView([FromQuery] string categoryName, [FromQuery] string viewName)
        {
            try
            {

                // 2. 根据分类ID和视图名执行删除
                bool result = _viewManagementService.DeleteView(categoryName, viewName);
                if (result)
                {
                    return Ok();
                }
                return NotFound("未找到对应的视图");
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = ex.Message });
            }
        }
        // 删除视图的所有内容
        [HttpDelete("charts/delete/{viewName}")]
        public IActionResult DeleteViews(string viewName)
        {
            try
            {
                var result = _viewManagementService.DeleteViews(viewName);
                if (result)
                    return Ok(new { Success = true, Message = "视图删除成功" });
                return StatusCode(500, new { Success = false, Message = "视图删除失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "视图删除失败");
                return StatusCode(500, new { Success = false, Message = "服务器错误" });
            }
        }
    }
}
